// pages/Order/TravelOrder/TravelOrder.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetTravelOrderForm } from '../../../api/petOrder';
import { throttle } from '../../../utils/util';
import { ACCESS_TOKEN } from '../../../utils/types';
import { getToken , codeLogin } from '../../../api/login';
import { getUser } from '../../../api/user';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    page: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    dataList: [],
    tabList: [
      { id: '', name: '全部'},{ id: '0', name: '待支付'},{ id: '1', name: '已预约'},{ id: '2', name: '已取消'},{ id: '3', name: '已完成'},
    ],
    active: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(wx.getStorageSync(ACCESS_TOKEN) == null || wx.getStorageSync(ACCESS_TOKEN) == ''){
      this.login();
    }else{
      this._queryPetTravelOrderForm()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._queryPetTravelOrderForm()
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._queryPetTravelOrderForm()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  _queryPetTravelOrderForm(){
    let _this = this;
    queryPetTravelOrderForm({page: _this.data.page,orderStatus: _this.data.active})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        var arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          if(element.orderStatus == '0'){
            var reg = new RegExp(/-/,'g');
            var createTime = element.createTime.replace(reg,'/');
            console.log(createTime,'createTime');
            var closeTime = new Date(createTime).getTime() - new Date().getTime() + 30 * 60 * 1000;
            console.log(closeTime,'closeTime')
            element.closeTime = closeTime;
          }
          arr.push(element);
        }
        if(_this.data.page == 0){
          list = arr;
        }else{
          list = list.concat(arr);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // tab切换
  onChange(e){
    console.log(e)
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      active: e.detail.name,
    })
    this._queryPetTravelOrderForm();
  },
  // 跳转详情
  detail(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/Order/TravelOrderDetail/TravelOrderDetail?orderCode=${item.orderCode}`,
      events: {
        'updateOrder': function(res){
          _this.setData({
            page: 0,
            isReachBottom: false,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
          _this._queryPetTravelOrderForm()
        }
      }
    })
  },
  timeFinish(){
    console.log('倒计时结束');
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._queryPetTravelOrderForm();
  },
  // 登录
  login(){
    let _this = this;
    // 获取服务器token
    getToken().then(res => {
      if(res.success){
        wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
        wx.login({
          success: logRes => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log(logRes,'logRes')
            if (logRes.code) {
              codeLogin(logRes.code,_this.data.parentUserId)
              .then(async rres => {
                console.log(rres,'第一次登录返回的rres')
                if(rres.success){
                  wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                  wx.setStorageSync('expires_in', rres.expires_in);
                  getUser({})
                  .then(user => {
                    if(user.success){
                      wx.setStorageSync('userId', user.data.userId)
                      wx.setStorageSync('phone', user.data.phone)
                      _this._queryPetTravelOrderForm()
                    }
                  })
                }else{
                  wx.showToast({
                    title: rres.errMessage,
                    icon: 'none',
                  })
                }
              })
            } else {
              wx.showToast({
                title: logRes.errMsg,
                icon: 'none',
              })
            }
          },
          fail:function(err){
            console.log(err,'err')
          }
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  }
})